dojo.require("dojox.cometd");
dojo.require("dojox.cometd.timestamp");

var room = {
	_last: "",
	_username: null,
	_connected: true,
	_uid:null,
	
	join: function(name){
	
		if (name == null || name.length == 0) {
			alert('Please enter a username!');
			return;
		}
		//comet server location
		var loc = //(new String(document.location).replace(/http:\/\/[^\/]*/, '').replace(/\/test\/.*$/, '')) +
		"/truckserver/cometd";
		dojox.cometd.init(loc);
		// For x-domain test change line above to:
		// dojox.cometd.init("http://127.0.0.1:8080/cometd/cometd");
		this._connected = true;
		
		this._username = name;
		
		// subscribe and join
		dojox.cometd.startBatch();
		// use echo function, not broadcast.
		dojox.cometd.subscribe("/service/srcar", room, "_report");
		//append a null string to user to case user to string
		dojox.cometd.publish("/service/srcar", {
			user: room._username+"",
			join: true,
			data: room._username + " has joined"
		});
		dojox.cometd.endBatch();
		
		// handle cometd failures while in the room
		if (room._meta) {
			dojo.unsubscribe(room._meta, null, null);
		}
		room._meta = dojo.subscribe("/cometd/meta", this, function(e){
			// console.debug(e);
			if (e.action == "handshake") {
				if (e.reestablish) {
					if (e.successful) {
						dojox.cometd.subscribe("/service/srcar", room, "_report");
						dojox.cometd.publish("/service/srcar", {
							user: room._username,
							join: true,
							data: room._username + " has re-joined"
						});
					}
					room._report({
						data: {
							join: true,
							user: "SERVER",
							data: "handshake " + e.successful ? "Handshake OK" : "Failed"
						}
					});
				}
			}
			else 
				if (e.action == "connect") {
					if (e.successful && !this._connected) {
						room._report({
							data: {
								join: true,
								user: "SERVER",
								data: "reconnected!"
							}
						});
					}
					if (!e.successful && this._connected) {
						room._report({
							data: {
								leave: true,
								user: "SERVER",
								data: "disconnected!"
							}
						});
					}
					this._connected = e.successful;
				}
		});
	},
	
	leave: function(){
		if (!room._username) {
			return;
		}
		
		if (room._meta) {
			dojo.unsubscribe(room._meta);
		}
		room._meta = null;
		
		dojox.cometd.startBatch();
		dojox.cometd.unsubscribe("/service/srcar", room, "_report");
		dojox.cometd.publish("/service/srcar", {
			user: room._username,
			leave: true,
			data: room._username + " has left"
		});
		dojox.cometd.endBatch();
		
		
		dojox.cometd.disconnect();
		var report = dojo.byId('report');
		report.innerHTML = "<span class=\"alert\"><span class=\"text\">" + room._username + " has left the chat room</span></span><br/>";
		room._last = "";
		room._username = null;
	},
	// send to server
	report: function(text){
		if (!text || !text.length||!room._connected) {
			return false;
		}
		//cast user to string		
		dojox.cometd.publish("/service/srcar", {
			user: room._username+"",
			uid: room._uid,
			report: true,
			data: text
		});
	},
	randomString:function(string_length) {
		var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";		
		var randomstring = '';
		for (var i=0; i<string_length; i++) {
			var rnum = Math.floor(Math.random() * chars.length);
			randomstring += chars.substring(rnum,rnum+1);
		}
		return randomstring;
	},
	// feed back from server
	_report: function(message){
		var report = dojo.byId('report');		
		if (!message.data) {
			// console.debug("bad message format " + message);
			return;
		}
		
		var from = message.data.user;
		var special = message.data.join || message.data.leave;		
		if( message.data.join &&from==room._username){				
			hideLogin();
			//set the uid
			room._uid=message.data.uid;			
		}
		var text = message.data.data;
		if (!text) {
			return;
		}
		
		if (!special && from == room._last) {
			from = "...";
		}
		else {			
			room._last = from;
			from += ":";
		}
		
		if (special) {
			report.innerHTML = "<span class=\"alert\"><span class=\"from\">" + from + "&nbsp;</span><span class=\"text\">" + text + "</span></span><br/>";
			room._last = "";
		}
		else {
			report.innerHTML = "<span class=\"from\">" + from + "&nbsp;</span><span class=\"text\">" + text + "</span><br/>";
		}
		//show neighbours
		var neighbours=message.data.surrounded;
		if (neighbours!=null){
			report.innerHTML+="Surrounded Cars:<BR>"+neighbours;
		}
		carManager.updateCars(neighbours);
		report.scrollTop = report.scrollHeight - report.clientHeight;
	},
	
	_init: function(){		
		room.join(room.randomString(8));								
	}
};

//dojo.addOnLoad(room, "_init");
dojo.addOnUnload(room, "leave");
//vim:ts=4:noet:


